package cn.wolfcode.wolf2w.listener;

import cn.wolfcode.wolf2w.cache.service.IStrategyStatisVORedisService;
import cn.wolfcode.wolf2w.cache.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.service.IStrategyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * redis 初始化话监听器
 */
//@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IStrategyStatisVORedisService strategyStatisVORedisService;

    //当容器调用这个方法时,马上执行下面逻辑
    //spring容器启动之后,初始化完成后马上执行
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("--------初始化-vo-开始------------");

        //查询数据库中所有攻略
        List<Strategy> list = strategyService.list();
        for (Strategy strategy : list) {
            //判断vo对象是否已经存在redis中,如果存在,直接跳过
            if (strategyStatisVORedisService.isStrategyVoExists(strategy.getId())){
                continue;
            }
            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(strategy,vo);
            vo.setStrategyId(strategy.getId());
            //将vo对象缓存到redis中
            strategyStatisVORedisService.setStrategyStatisVO(vo);
        }
        System.out.println("--------初始化-vo-结束------------");
    }
}
